from django.http import HttpResponseBadRequest
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View # 导入django的View包
# Create your views here.
from home.models import ArticleCategory, Article
from home.models import Comment
import json


class IndexView(View):
    def get(self, request):
        # 1、获取所有分类信息数据
        categories = ArticleCategory.objects.all()
        # 2、接收用户点击的分类id
        cat_id = request.GET.get('cat_id', 1)
        # 3、根据分类id进行分类的查询
        try:
            category = ArticleCategory.objects.get(id=cat_id)
        except ArticleCategory.DoesNotExist:
            return HttpResponseBadRequest('此分类信息不存在')
        # 4、获取分页参数
        page_index = request.GET.get('page_index', 1)  # 页码
        page_size = request.GET.get('page_size', 2)  # 页容量
        # 5、根据分类信息查询该分类下的所有文章数据
        articles = Article.objects.filter(category=category)
        art = Article.objects.filter(category=category).order_by('-total_views')[:2]
        # 6、创建分页器
        from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger  # 导入django分页插件
        pages = Paginator(articles, page_size)  # 对查询到的数据对象articles进行分页，设置超过指定页容量就分页

        try:
            list = pages.page(page_index)  # 获取当前页面的记录
        except PageNotAnInteger:
            list = pages.page(1)  # 如果用户输入的页面不是整数时，显示第1页的内容
        except EmptyPage:
            list = pages.page(pages.num_pages)  # 如果用户输入的页数不在系统的页码列表中时,显示最后一页的内容
        # 4、组织数据传递给模板
        comm = Comment.objects.order_by('-created_time')[0:2]
        art_a = Article.objects.all().order_by('-create_time')[:3]
        if request.COOKIES.get("login_name") is not None:
            username = json.loads(request.COOKIES.get("login_name"))
        else:
            username = ""

        context = {
            'categories': categories,
            'category': category,
            'articles': list,
            'cat_id':cat_id,
            'art':art,
            "comms": comm,
            'art_a': art_a,
            'username': username

        }
        print(list)
        return render(request, 'index.html', context=context)


class DetailsView(View):
    def get(self, request):
        art_id = request.GET.get('artid')
        try:
           article = Article.objects.get(id=art_id)
        except Article.DoesNotExist:
            return render(request,'404.html')
        article.total_views += 1
        article.save()
        comm = Comment.objects.filter(article=article).order_by('-created_time')
        art = Article.objects.all().order_by('-create_time')[:3]
        context={
            "article":article,
            "comm": comm,
            "art":art
        }
        return render(request, 'details.html', context=context)

    def post(self, request):
        user= request.user

        if user and user.is_authenticated:
            art_id = request.POST.get('art_id')
            content = request.POST.get('content')
            try:
               art = Article.objects.get(id=art_id)
            except Article.DoesNotExist:
               return HttpResponseBadRequest('该文章不存在')
            Comment.objects.create(content=content,article=art,user=user)
            art.comments_count += 1
            art.save()
            req_url = request.path + '?artid=' + art_id
            return redirect(req_url)
        else:
            return redirect(reverse("polls:login"))


class Shangcheng(View):
    def get(self,request):
        return render(request,'shangcheng.html')


